#import "FFmpegWrapper.h"
#import <AVFoundation/AVFoundation.h>

extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libswscale/swscale.h>
}

@interface FFmpegWrapper () {
    AVFormatContext* _formatContext;
    AVCodecContext* _videoCodecContext;
    AVCodecContext* _audioCodecContext;
    AVFrame* _frame;
    AVPacket* _packet;
    SwsContext* _swsContext;
    
    BOOL _isInitialized;
    BOOL _isPlaying;
    double _currentTime;
    double _duration;
}

@end

@implementation FFmpegWrapper

- (instancetype)init {
    self = [super init];
    if (self) {
        _formatContext = nullptr;
        _videoCodecContext = nullptr;
        _audioCodecContext = nullptr;
        _frame = nullptr;
        _packet = nullptr;
        _swsContext = nullptr;
        _isInitialized = NO;
        _isPlaying = NO;
        _currentTime = 0.0;
        _duration = 0.0;
    }
    return self;
}

- (BOOL)initialize {
    if (_isInitialized) {
        return YES;
    }
    
    // 初始化FFmpeg
    av_register_all();
    avformat_network_init();
    
    // 分配格式上下文
    _formatContext = avformat_alloc_context();
    if (!_formatContext) {
        NSLog(@"Failed to allocate format context");
        return NO;
    }
    
    // 分配帧和包
    _frame = av_frame_alloc();
    _packet = av_packet_alloc();
    
    if (!_frame || !_packet) {
        NSLog(@"Failed to allocate frame or packet");
        return NO;
    }
    
    _isInitialized = YES;
    NSLog(@"FFmpeg initialized successfully");
    return YES;
}

- (BOOL)openMedia:(NSString *)filePath {
    if (!_isInitialized) {
        NSLog(@"FFmpeg not initialized");
        return NO;
    }
    
    // 打开输入文件
    int ret = avformat_open_input(&_formatContext, [filePath UTF8String], nullptr, nullptr);
    if (ret < 0) {
        NSLog(@"Failed to open input file: %@", filePath);
        return NO;
    }
    
    // 查找流信息
    ret = avformat_find_stream_info(_formatContext, nullptr);
    if (ret < 0) {
        NSLog(@"Failed to find stream info");
        return NO;
    }
    
    // 设置解码器
    if (![self setupVideoDecoder] || ![self setupAudioDecoder]) {
        NSLog(@"Failed to setup decoders");
        return NO;
    }
    
    // 获取时长
    if (_formatContext->duration != AV_NOPTS_VALUE) {
        _duration = _formatContext->duration / (double)AV_TIME_BASE;
    }
    
    NSLog(@"Media opened successfully: %@", filePath);
    return YES;
}

- (NSDictionary *)getMediaInfo {
    if (!_formatContext) {
        return @{};
    }
    
    // 查找视频流
    int videoStreamIndex = -1;
    for (unsigned int i = 0; i < _formatContext->nb_streams; i++) {
        if (_formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStreamIndex = i;
            break;
        }
    }
    
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    
    if (videoStreamIndex >= 0) {
        AVStream* videoStream = _formatContext->streams[videoStreamIndex];
        info[@"width"] = @(videoStream->codecpar->width);
        info[@"height"] = @(videoStream->codecpar->height);
        info[@"duration"] = @(_duration);
        info[@"bitrate"] = @(_formatContext->bit_rate);
        
        // 获取编解码器名称
        AVCodec* codec = avcodec_find_decoder(videoStream->codecpar->codec_id);
        if (codec) {
            info[@"codec"] = [NSString stringWithUTF8String:codec->name];
        }
    }
    
    return [info copy];
}

- (BOOL)setupVideoDecoder {
    // 查找视频流
    int videoStreamIndex = -1;
    for (unsigned int i = 0; i < _formatContext->nb_streams; i++) {
        if (_formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoStreamIndex = i;
            break;
        }
    }
    
    if (videoStreamIndex < 0) {
        NSLog(@"No video stream found");
        return YES; // 没有视频流不算错误
    }
    
    // 获取解码器
    AVCodec* codec = avcodec_find_decoder(_formatContext->streams[videoStreamIndex]->codecpar->codec_id);
    if (!codec) {
        NSLog(@"Video codec not found");
        return NO;
    }
    
    // 创建解码器上下文
    _videoCodecContext = avcodec_alloc_context3(codec);
    if (!_videoCodecContext) {
        NSLog(@"Failed to allocate video codec context");
        return NO;
    }
    
    // 复制参数
    int ret = avcodec_parameters_to_context(_videoCodecContext, 
                                           _formatContext->streams[videoStreamIndex]->codecpar);
    if (ret < 0) {
        NSLog(@"Failed to copy codec parameters");
        return NO;
    }
    
    // 打开解码器
    ret = avcodec_open2(_videoCodecContext, codec, nullptr);
    if (ret < 0) {
        NSLog(@"Failed to open video codec");
        return NO;
    }
    
    NSLog(@"Video decoder setup successfully");
    return YES;
}

- (BOOL)setupAudioDecoder {
    // 查找音频流
    int audioStreamIndex = -1;
    for (unsigned int i = 0; i < _formatContext->nb_streams; i++) {
        if (_formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            audioStreamIndex = i;
            break;
        }
    }
    
    if (audioStreamIndex < 0) {
        NSLog(@"No audio stream found");
        return YES; // 没有音频流不算错误
    }
    
    // 获取解码器
    AVCodec* codec = avcodec_find_decoder(_formatContext->streams[audioStreamIndex]->codecpar->codec_id);
    if (!codec) {
        NSLog(@"Audio codec not found");
        return NO;
    }
    
    // 创建解码器上下文
    _audioCodecContext = avcodec_alloc_context3(codec);
    if (!_audioCodecContext) {
        NSLog(@"Failed to allocate audio codec context");
        return NO;
    }
    
    // 复制参数
    int ret = avcodec_parameters_to_context(_audioCodecContext, 
                                           _formatContext->streams[audioStreamIndex]->codecpar);
    if (ret < 0) {
        NSLog(@"Failed to copy codec parameters");
        return NO;
    }
    
    // 打开解码器
    ret = avcodec_open2(_audioCodecContext, codec, nullptr);
    if (ret < 0) {
        NSLog(@"Failed to open audio codec");
        return NO;
    }
    
    NSLog(@"Audio decoder setup successfully");
    return YES;
}

- (BOOL)play {
    if (!_isInitialized || !_formatContext) {
        return NO;
    }
    
    _isPlaying = YES;
    NSLog(@"Playback started");
    return YES;
}

- (BOOL)pause {
    _isPlaying = NO;
    NSLog(@"Playback paused");
    return YES;
}

- (BOOL)stop {
    _isPlaying = NO;
    _currentTime = 0.0;
    NSLog(@"Playback stopped");
    return YES;
}

- (BOOL)seek:(double)time {
    if (!_formatContext) {
        return NO;
    }
    
    int64_t timestamp = (int64_t)(time * AV_TIME_BASE);
    int ret = av_seek_frame(_formatContext, -1, timestamp, AVSEEK_FLAG_BACKWARD);
    if (ret < 0) {
        NSLog(@"Failed to seek");
        return NO;
    }
    
    _currentTime = time;
    NSLog(@"Seeked to: %f", time);
    return YES;
}

- (void)setVolume:(double)volume {
    // 音量控制实现
    NSLog(@"Volume set to: %f", volume);
}

- (void)cleanup {
    if (_swsContext) {
        sws_freeContext(_swsContext);
        _swsContext = nullptr;
    }
    
    if (_videoCodecContext) {
        avcodec_free_context(&_videoCodecContext);
    }
    
    if (_audioCodecContext) {
        avcodec_free_context(&_audioCodecContext);
    }
    
    if (_frame) {
        av_frame_free(&_frame);
    }
    
    if (_packet) {
        av_packet_free(&_packet);
    }
    
    if (_formatContext) {
        avformat_close_input(&_formatContext);
    }
    
    _isInitialized = NO;
    _isPlaying = NO;
}

@end
